package handlers

import (
	"fmt"
	"github.com/emicklei/go-restful"
	"kubeInstall/model"
	"kubeInstall/model/app"
	"kubeInstall/utils"
	"net/http"
)

const MASTER = "master"
const WORKER = "worker"

func CreateCluster(r *restful.Request, resp *restful.Response) {
	//将前端用户配置好的集群信息，写入数据库。
	var req model.Cluster
	if err := r.ReadEntity(&req); err != nil {
		RenderError(resp, "get Cluster from http request failed", http.StatusInternalServerError)
		return
	}

	//创建集群配置
	cluster, err := req.Create()
	if err != nil {
		RenderError(resp, fmt.Sprintf("add Cluster failed %v\n", err), http.StatusBadRequest)
		return
	}

	// 更新host信息，绑定集群

	for _, h := range req.MasterNode {
		h.ClusterId = cluster.ID
		h.Role = MASTER
		h.Used = true
		h.Update(h.ID)
	}

	for _, h := range req.WorkerNode {
		h.ClusterId = cluster.ID
		h.Role = WORKER
		h.Used = true
		h.Update(h.ID)
	}

	resp.WriteHeaderAndJson(http.StatusOK, cluster, restful.MIME_JSON)
}

func InstallCluster(r *restful.Request, resp *restful.Response) {
	//读取数据库配置。根据配置，使用kubeadm安装集群。
	clusterId := r.QueryParameter("cluster_id")

	if clusterId == "" {
		RenderError(resp, fmt.Sprintf("get cluster id from http query failed!"), http.StatusBadRequest)
		return
	}

	//获取集群配置
	clusterInfo, err := GetClusterInfo(clusterId)

	if err != nil {
		RenderError(resp, fmt.Sprintf("get cluster failed! error is:  %v\n", err), http.StatusBadRequest)
		return
	}

	go func() {
		installCluster(clusterInfo)
		//bug
		utils.Done <- true
	}()
	for {
		select {
		case data := <-utils.MsgQueue:
			//data transfer to websocket
			fmt.Println("result is ", string(data))
		case <-utils.Done:
			fmt.Println("done for task!")
			return
		}
	}
}

func installCluster(cluster *model.Cluster) error {

	nFSServerIp := "192.168.169.6"
	nFSServerPath := "/opt/data"
	//配置基础环境：docker，rpm包等等。
	for _, node := range cluster.MasterNode {
		cluster.InitBaseEnv(node, cluster.ClusterHostNameMap, nFSServerIp, nFSServerPath)
	}

	for _, node := range cluster.WorkerNode {
		cluster.InitBaseEnv(node, cluster.ClusterHostNameMap, nFSServerIp, nFSServerPath)
	}

	//安装master0，初始化集群。
	joinOpts, err := cluster.InitMaster0(cluster)
	if err != nil {
		utils.Error("install cluster failed! error is:  %v\n", err)
		return err
	}

	if len(cluster.MasterNode) > 1 {
		//安装多节点master
		//安装HA proxy
		for _, m := range cluster.MasterNode[1:] {
			err = cluster.AddMaster(m, joinOpts)
			if err != nil {
				utils.Error("add cluster master node :%v failed! error is:  %v\n", m, err)
				return err
			}
		}
	}

	//加入worker节点
	for _, w := range cluster.WorkerNode {

		if cluster.VIP != "" {
			joinOpts.MasterIP = cluster.VIP + ":6443"
		}

		err = cluster.AddWorker(w, joinOpts)
		if err != nil {
			utils.Error("add cluster worker node :%v failed! error is:  %v\n", w, err)
			return err
		}
	}

	// 安装node检查插件
	npd := &app.NPD{
	}

	cluster.InstallApp(npd)

	//安装存储插件
	nfs := &model.StoragePluginNFS{
		NFSServerIp:   nFSServerIp,
		NFSServerPath: nFSServerPath,
	}
	cluster.InstallApp(nfs)

	//安装网络插件
	calico := &model.NetworkPluginCalico{}
	cluster.InstallApp(calico)

	// 安装DNS 缓存

	dnsIp := cluster.Master0Handler.GetDNSServerIp()
	dns := &app.DnsCache{
		ClusterName: cluster.ClusterName,
		LocalDNS:    "169.254.25.10",
		DNSServer:   dnsIp,
	}
	cluster.InstallApp(dns)

	// 安装监控插件
	monitor := &app.Monitor{
	}

	cluster.InstallApp(monitor)

	// 安装metric server 监控插件
	metric := &app.MetricServer{
	}

	cluster.InstallApp(metric)

	// 安装log server EFK
	log := &app.LogServer{}
	cluster.InstallApp(log)

	// 安装ingress
	ingress := &app.Ingress{
		IngressNodeName: cluster.WorkerNode[0].HostName,
	}
	cluster.InstallApp(ingress)

	// 配置APP插件ingress
	ingressForApp := &app.IngressForAPP{
		DomainName:  cluster.DomainName,
		ClusterName: cluster.ClusterName,
	}

	cluster.InstallApp(ingressForApp)

	return nil
}
func GetClusterInfo(clusterId string) (*model.Cluster, error) {
	var cluster model.Cluster

	clusterInfo, err := cluster.Get(clusterId)
	if err != nil {
		return nil, err
	}

	//查询节点信息。
	var host model.Host
	masterNode, err := host.GetHostRoleByClusterId(clusterId, MASTER)
	if err != nil {
		return nil, err
	}
	workerNode, err := host.GetHostRoleByClusterId(clusterId, WORKER)
	if err != nil {
		return nil, err
	}

	hosts := make([]model.HostNameAndIP, 0)

	for _, m := range masterNode {

		host := model.HostNameAndIP{
			HostName: m.HostName,
			Ip:       m.IP,
		}
		hosts = append(hosts, host)
	}

	for _, m := range workerNode {
		host := model.HostNameAndIP{
			HostName: m.HostName,
			Ip:       m.IP,
		}
		hosts = append(hosts, host)
	}

	clusterInfo.MasterNode = masterNode
	clusterInfo.WorkerNode = workerNode
	clusterInfo.ClusterHostNameMap = hosts

	return &clusterInfo, nil
}

func GetCluster(r *restful.Request, resp *restful.Response) {
	//读取数据库配置。返回集群信息

	clusterId := r.QueryParameter("cluster_id")

	if clusterId == "" {
		RenderError(resp, fmt.Sprintf("get cluster id from http query failed!"), http.StatusBadRequest)
		return
	}

	clusterInfo, err := GetClusterInfo(clusterId)

	if err != nil {
		RenderError(resp, fmt.Sprintf("get cluster failed! error is:  %v\n", err), http.StatusBadRequest)
		return
	}

	resp.WriteHeaderAndJson(http.StatusOK, clusterInfo, restful.MIME_JSON)

}

func DeleteCluster(r *restful.Request, resp *restful.Response) {
	//读取数据库配置。根据配置，使用kubeadm卸载集群。
}
